package com.demo.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.domain.SysRole;
import com.demo.mapper.SysRoleMapper;
import com.demo.model.R;
import com.demo.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;


/**
 * 1 查询方法  sys_role_query
 * 2 修改     sys_role_update
 * 3 增加     sys_role_create
 * 4 删除     sys_role_delete
 * 权限管理的权限
 */
@RestController
@RequestMapping("/roles")
@Api(tags = "角色管理")
public class SysRoleController {


    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping
    @ApiOperation(value = "分页查询")
    @PreAuthorize("hasAuthority('sys_role_query')")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="current" ,value ="当前页" ),
            @ApiImplicitParam(name ="size" ,value ="每页大小" ),
            @ApiImplicitParam(name ="name" ,value ="角色名称" )

    })
    public R<Page<SysRole>> roleFindByPage(Page<SysRole>page,String name){
        //根据更新时间倒序查询
        page.addOrder(OrderItem.desc("last_update_time"));
        return R.ok(sysRoleService.findByPage(page,name));
    }

    @PostMapping
    @PreAuthorize("hasAuthority('sys_role_create')")
    @ApiOperation(value = "角色新增")
    public R add(@RequestBody @Valid SysRole sysRole){
        boolean save = sysRoleService.save(sysRole);
        if(save){
            return R.ok("角色新增成功");
        }
        return R.fail("角色新增失败");
    }


    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys_role_create')")
    @ApiOperation(value = "删除角色数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="ids" ,value ="要删除角色id集合" ),
    })
    public R delete(@RequestBody @Valid String []ids){
        if(null == ids || ids.length == 0){
            return R.fail("删除的数据不能为空");
        }
        boolean delete = sysRoleService.removeByIds(Arrays.asList(ids));
        if(delete){
            return R.ok("角色删除成功");
        }
        return R.fail("角色删除失败");
    }
}
